/*
 * @Description: 登录组件
 * @Author: Rfan
 * @Date: 2023-01-10 16:05:57
 * @LastEditTime: 2023-01-10 16:13:12
 */

import { useState } from 'react';
import { Button, Form, Input } from 'antd';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import classNames from 'classnames/bind';
import JSEncrypt from 'jsencrypt';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { getPublicKey } from '@/api/userOpt';
import { useFormatMessage } from '@/utils/intlHelpers';
import { appActions, appState } from '@/store/mobx';
import { routerActions } from '@/store/routerStore';
import type { ValidateErrorEntity } from 'rc-field-form/lib/interface';
import type { ILogin } from '@/view/Login';
import styles from '../styles/index.module.scss';

const cx = classNames.bind(styles);

const LoginPane = (props: any) => {
  const { changePane } = props;
  const formatMessage = useFormatMessage();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  // 获取跳转路径
  const redirect = searchParams.get('redirect') || '';

  const [loading, setLoading] = useState<boolean>(false);

  /**
   * 登录方法，处理跳转，权限等
   */
  const loginFunc = (userInfo: ILogin) => {
    appActions
      .login(userInfo)
      .then(() => {
        const url = redirect && redirect !== '/' ? redirect : '';

        // appActions.getUnitList();
        routerActions.getNavList().then((res: any[]) => {
          if (!url) {
            const subSysNodes = res.filter((item) => item.pid === 0);
            if (subSysNodes.length <= 1) {
              navigate('/url');
            } else {
              changePane(false);
            }
          }
        });
        if (url) {
          navigate(url);
        }
      })
      .finally(() => {
        setLoading(false);
      });
  };

  /**
   * @description: 登录表单提交
   * @param {ILogin} val 登录表单信息
   */
  const onFinish: (val: ILogin) => void = (val: ILogin) => {
    console.log('Success:', val);
    setLoading(true);
    if (appState.loginKey) {
      const encrypt = new JSEncrypt();
      // 设置公钥
      encrypt.setPublicKey(appState.loginKey);
      const params = JSON.parse(JSON.stringify(val));
      // // 加密密码
      // params.username = encrypt.encrypt(val.username);
      // params.password = encrypt.encrypt(val.password);
      params.username = val.username;
      params.password = val.password;

      params.orgName = val.username;

      // 登录
      loginFunc(params);
    } else {
      // 没有存公钥时先请求公钥
      getPublicKey()
        .then((res) => {
          // mobx设置公钥
          appActions.setPublicKey(res.data);
          // 重新调用完成方法
          onFinish(val);
        })
        .finally(() => {
          setLoading(false);
        });
    }
  };

  const onFinishFailed = (errorInfo: ValidateErrorEntity) => {
    console.log('Failed:', errorInfo);
  };

  return (
    <div className={cx('login-pane')}>
      <div className={cx('login-wrapper')}>
        <Form
          name="basic"
          layout="vertical"
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label={formatMessage('login.username')}
            name="username"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input
              prefix={<UserOutlined className={cx('site-form-item-icon')} />}
              placeholder={formatMessage('login.usernamePlaceholder')}
            />
          </Form.Item>

          <Form.Item
            label={formatMessage('login.password')}
            name="password"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password
              prefix={<LockOutlined className={cx('site-form-item-icon')} />}
              placeholder={formatMessage('login.passwordPlaceholder')}
            />
          </Form.Item>

          <Form.Item>
            <Button type="primary" size="large" htmlType="submit" loading={loading} block>
              {formatMessage('login.loginBtnText')}
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default LoginPane;
